<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Models\LuoRule;
use App\Models\LuoAdminUser;

class Luo extends Model {
    use SoftDeletes;

    protected $table = 'luo';
    protected $fillable = ['name', 'pic'];
    protected $dates = ['deleted_at'];

    public function user_relation_list() {
        return $this->hasMany('App\Models\LuoUser');
    }

    public static function add($name, $pic) {
        return Luo::create(['name' => $name, 'pic' => $pic]);
    }

    public static function get_by_name($name) {
        return Luo::where('name', $name)->first();
    }

    public static function check_name($name, $id=null){
        $l = Luo::withTrashed()->where('name', $name)->first();
        if($l && $l->id != $id) return true;
    }

    public function rule() {
        return $this->hasOne('App\Models\LuoRule', 'luo_id', 'id');
    }

    public function set_rule($score) {
        $score = $score? intval($score):0;
        if($this->rule) {
            $this->rule->score = $score;
            $this->rule->save();
        }else{
            LuoRule::add($this->id, $score);
        }
    }

    public function admin() {
        return $this->hasOne('App\Models\LuoAdminUser', 'luo_id', 'id');
    }

    public function set_admin($name, $tel) {
        if($this->admin) {
            $this->admin->name = $name;
            $this->admin->tel = $tel;
            $this->admin->save();
        }else{
            LuoAdminUser::add($this->id, $name, $tel);
        }
    }

    public function posts() {
        return $this->hasMany('App\Models\Post', 'luo_id', 'id');
    }

    public function get_posts($status=1) {
        return $this->posts()->where('status', $status)->paginate(20);
    }
}
